package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.mongo.FollowUser;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * 小视频服务接口实现类
 */
@Service
public class VideoApiImpl implements VideoApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 发布小视频
     * videoThumbnail:视频封面文件
     * videoFile:视频文件
     */
    @Override
    public void saveSmallVideos(Video video) {
        video.setId(ObjectId.get());
        video.setCreated(System.currentTimeMillis());
        mongoTemplate.insert(video);
    }

    /**
     * 小视频分页列表数据
     */
    @Override
    public PageResult<Video> findPageBySmallVideos(long page, long pagesize) {
        //1.查询总记录数
        Query query = new Query();
        long counts = mongoTemplate.count(query, Video.class);
        //2.查询当前页面需要展示的数据
        query.limit((int)pagesize).skip((page-1)*pagesize);
        //根据视频发布时间排序 将视频发布时间最新的放前面展示
        query.with(Sort.by(Sort.Direction.DESC,"created"));
        List<Video> videoList = mongoTemplate.find(query, Video.class);
        //3.封装数据返回
        Long pages = counts/pagesize + (counts%pagesize > 0 ? 1:0);
        return new PageResult<>(counts,(long)pagesize,pages,(long)page,videoList);
    }

    /**
     * 关注用户
     * followUserId:被关注的用户id
     */
    @Override
    public void userFocus(FollowUser followUser) {
        followUser.setId(ObjectId.get());
        followUser.setCreated(System.currentTimeMillis());
        mongoTemplate.insert(followUser);

        //如果相互关注 往好友表插入2条记录
    }


    /**
     * 取消关注用户
     * followUserId:被取消关注的用户id
     */
    @Override
    public void userUnFocus(FollowUser followUser) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(followUser.getUserId()).and("followUserId").is(followUser.getFollowUserId()));
        mongoTemplate.remove(query,FollowUser.class);

        //如果取消关注 好友表删除对应的2条记录
    }
}
